package mango.service.db.task;

import mango.Mango;

public class DBTaskHandler implements Runnable {
    private DBTaskProcessable currentTask;
    private boolean shutdown = false;
    
    private static int handler_size = 0;
    
    public DBTaskHandler() {
        Thread t = new Thread(this);
        t.setName("DBTaskHandler_" + handler_size++);
        t.start();
    }

    public synchronized void postClose() {
        if (this.currentTask == null) {
            shutdown = true;
        }
    }

    public synchronized boolean addTask(DBTaskProcessable task) {
        if (this.currentTask == null) {
            this.currentTask = task;
            this.notify();
            return true;
        }
        return false;
    }

    public void run() {
        while (!shutdown) {
            try {
                if (this.currentTask != null) {
                    boolean ret = this.currentTask.process();
                    if(ret) {
                        this.currentTask.onBack();
                        this.currentTask = null;
                    }
                }
                else {
                    synchronized (this) {
                        wait(50);
                    }
                }
            }
            catch (Exception e) {
                Mango.getLog().error("DBTaskHandler handle error !!!", e);
            }
        }
    }
}
